package czk.concrent.enjoymodel;

/**
 * volatile改变两阶段终止模式
 * @Author:ChenZhangKun
 * @Date: 2020/6/3 21:53
 */
public class Test2 {
    // 终止标记
    private volatile static boolean flag=false;
    private Thread thread=null;
    public static void main(String[] args) throws InterruptedException {
        Test2 test2=new Test2();
        test2.start();
        Thread.sleep(2*1000);
        test2.stop();

    }
    public void start(){
        thread=new Thread(()->{
            while (true){
                if (flag){
                    System.out.println("循环打断终止后事");
                    break;
                }
                try {
                    Thread.sleep(1*1000);
                    System.out.println("循环继续，没被打断");
                } catch (InterruptedException e) {
                    // 注意sleep被打断后，会清除打断标记
                    e.printStackTrace();
                }

            }
        });
        thread.start();
    }
    public void stop(){
        flag=true;
        // 叫醒线程
        thread.interrupt();
    }
}
